const CryptoJS = require('aes_util.js') //参数加密
var app = getApp();
// var host = 'https://lansheng.njrgrj.com/LanShengDaSha.Server/';
var host = 'https://lansheng-uat.njrgrj.com/LanShengDaSha.Server/';
var encryptedN = null; //加密后的参数
var header = {
  'content-type': "application/x-www-form-urlencoded",
  'Authorization': "",
  'mobile': '0',
  'UserName': "",
  'Cache-Control': 'max-age=2000000, no-cache'
}
/**
 * post请求调用  
 */
function post(url, params, onSuccess, onFailed) {
  if (params != null) {
    encryptedN = CryptoJS.AesEncrypt(params);
  }
  // console.log("请求方式：", "POST")
  // console.log("当前请求参数加密后的结果:" + encryptedN)
  wx.getStorage({
    key: 'UserInfo',
    success: function(res) {
      // console.log(JSON.stringify(res))
      if (res != null) {
        header.Authorization = "BasicAuth " + res.data.Ticket;
        header.UserName = res.data.AppLogin.LoginID;
        // console.log(JSON.stringify(header))
        request(url, encryptedN, "POST", onSuccess, onFailed);
      }
    }
  })
}

/**
 * get请求调用
 */
function get(url, params, onSuccess, onFailed) {

  if (params != null) {
    encryptedN = CryptoJS.AesEncrypt(params);
  }
  wx.getStorage({
    key: 'UserInfo',
    success: function(res) {
      // console.log(JSON.stringify(res)+"-----------------请求")
      if (res != null) {
        header.Authorization = "BasicAuth " + res.data.Ticket;
        header.UserName = res.data.AppLogin.LoginID;
        // console.log(wx.getStorageSync('UserInfo').ProjectGuid)
        request(url + "?" + encryptedN, encryptedN, "GET", onSuccess, onFailed);
      }
    }
  })
}

function dologin(url, params, onSuccess, onFailed) {
  // console.log(JSON.stringify(params))
  if (params != null) {
    encryptedN = CryptoJS.AesEncrypt(params);
    if (wx.getStorageSync('openid') != undefined && wx.getStorageSync('openid') != '') {
      encryptedN = "keypwds=" + encryptedN + '&OpenId=' + wx.getStorageSync('openid');
    } else {
      encryptedN = "keypwds=" + encryptedN
    }
  }
  request(url + "?" + encryptedN, null, "GET", onSuccess, onFailed);
}

//获取数据字典
function getDic(url, params, onSuccess, onFailed) {
  request(url, null, "GET", onSuccess, onFailed);
}

/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */
function request(url, params, method, onSuccess, onFailed) {
  // console.log('请求的地址', url)
  wx.showLoading({
    title: "正在加载中...",
  })
  wx.request({
    url: host + url, //服务地址+接口地址
    data: dealParams(params),
    method: method,
    header: header,
    success: function(res) {
      wx.hideLoading();
      // console.log('响应：', res.data);
      if (res.data) {
        //状态码200，请求成功！
        if (res.statusCode == 200) {
          onSuccess(res.data); //request success
        } else {
          //非200，打出异常信息
          onFailed(res.data.Message); //request failed
        }
      }
    },
    fail: function(error) {
      wx.hideLoading();
      onFailed(""); //failure for other reasons
      var errInfo = {
        productname: '兰生大厦',
        extend: '',
        statecode: 'error',
        loginId: wx.getStorageSync('UserInfo').AppLogin.LoginID
      }
      // post(apiInfo.SendAppJsErrorApi, errInfo, function(res) {}, function(err) {})
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '当前网络不佳，请稍后再试！',
        success: function() {
          //request(url, params, method, onSuccess, onFailed)
          wx.onNetworkStatusChange(function(res) {
            if (res.isConnected == false || res.networkType == '2g' || res.networkType == '2G') {
              wx.navigateTo({
                url: '../error/error?title=' + '网络连接异常' + '&Tips=' + '网络连接失败' + '&proposal=' + '请检查您的网络设置或者重新加载',
              })
            }
          })
        }
      })
      wx.navigateTo({
        url: '../error/error?title=' + '数据请求异常' + '&Tips=' + '获取数据失败' + '&proposal=' + '请重新加载',
      })
    }
  })
}

/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
  // console.log("请求参数:", params)
  return params;
}


//暴露接口
module.exports = {
  GetValidateRequest: get, //带验证的get请求
  PostValidateRequest: post, //带验证的post请求
  dologinRequest: dologin, //登录
  getDicRequest: getDic, //获取数据字典,
  uploadUrl: host + "Upload",
  host: host, //server地址
  apiInfo: {
    GetSchedulingAndUsesNewApi: 'api/LanShengMobile/GetSchedulingAndUsesNew', //获取值班人员和工程人员
    GetWorkOrderSearch2Api: 'api/Project_WorkOrders/GetSearch3', //获取工单数据（物业角色首页数据）
    GetProjectTxlMobileApi: 'api/Mobile/GetProjectTxlMobile', //获取通讯录
    GetWorkOrderInfoApi: "api/LanShengMobile/GetWorkOrdersInfo", //工单详情
    AddCxgdApi: "api/LanShengMobile/AddCxgd", //撤销工单
    UpdateFpRecordApi: 'api/LanShengMobile/UpdateFpRecord', //分配工单
    AcceptWorkOrdersApi: "api/LanShengMobile/AcceptWorkOrders", //接受、审核工单
    NoAcceptWorkOrders: 'api/LanShengMobile/NoAcceptWorkOrders', //审核不通过
    OneClickRepairInfoApi: "api/LanShengMobile/OneClickRepairInfo", //评价接口（好评、未完成评价、一键返修）
    UserLogin: 'api/AppLogin/GetLogin', //登录
    GetAllDictionary: 'api/Login/GetAllDictionary', //获取数据字典
    ProjectUpdatePwdApi: 'api/Mobile/UpdatePwd', //修改密码
    UpdataFrameProjectUserMobileApi: 'api/Frame_ProjectUser/PostUpdateMobile', //修改用户手机号
    Project_GetProjectRegionApi: 'api/LanShengMobile/GetProjectRegion', //获取区域
    Project_GetProjectBuildingApi: 'api/LanShengMobile/GetProjectBuilding', //获取建筑
    Project_GetProjectFloorApi: 'api/LanShengMobile/GetProjectFloor', //获取楼层
    Project_GetProjectRoomApi: 'api/LanShengMobile/GetProjectRoom', //获取房间
    GetProjectWyOrdersMobileApi: 'api/Mobile/GetProjectWyOrdersMobile', //故障类型
    AddWorkOrderApi: "api/LanShengMobile/AddWorkOrder", //新增工单
    AddWxjlApi: 'api/LanShengMobile/AddWxjl', //新增维修记录
    ProjectGetSearchMobileApi: 'api/LanShengMobile/GetSearchMobile', //移动端搜索工单
    Project_GetHourseRoomMobileApi: 'api/Mobile/GetHourseRoomMobile', //分页获取房间信息
    Project_GetWorkOrderSearchApi: 'api/LanShengMobile/GetWorkOrderSearch', //工单列表
    GetKeyWordsApi: 'api/LanShengMobile/GetKeyWords',//获取客服撤销工单的撤销原因
    GetEquipmentBySpaceGuidApi: 'api/LanShengMobile/GetEquipmentBySpaceGuid',//获取空间设备

    //设备信息
    GetEquipmentSearchApi: 'api/LanShengMobile/GetEquipmentSearch', //设备信息列表
    GetMasterSysDictionaryApi: 'api/LanShengMobile/GetMasterSysDictionary', //设备分类
    GetMaterClassifyDictionaryApi: 'api/LanShengMobile/GetMaterClassifyDictionary', //设备
    Project_GetEquipDetailMobileApi: 'api/LanShengMobile/GetEquipmentDetail', //设备台账详情信息

    //附件上传
    MultipleFileUploadMobileApi: 'api/LanShengMobile/MultipleFileUploadMobile',
    MultipleFileDeleteMobileApi: 'api/LanShengMobile/MultipleFileDeleteMobile',//附件删除

    //日常巡检
    GetInspectTaskListMobileApi: 'api/LanShengMobile/GetInspectTaskListMobile', //获取巡检点集合列表
    GetHistoryInspectTaskListMobileApi: 'api/LanShengMobile/GetHistoryInspectTaskListMobile',
    GetFinishInspectTaskDetailApi: 'api/LanShengMobile/GetFinishInspectTaskDetail', //获取历史任务详情
    AddTaskRecordApi: 'api/LanShengMobile/AddTaskRecord', //新增巡检内容
    GetInspectTaskDetailsApi: 'api/LanShengMobile/GetInspectTaskDetails', //获取巡检点集合列表
    GetGuidByCodeApi: 'api/LanShengMobile/GetGuidByCode', //扫一扫获取设备、设备间RowGuid
    GetProjectXjFormMobileApi: 'api/LanShengMobile/GetProjectXjFormMobile', //扫一扫获取任务
    GetInspectTaskLocationApi: 'api/LanShengMobile/GetInspectTaskLocation', //获取当前任务的位置


    //日志
    SendAppJsErrorApi: 'api/LanShengMobile/sendAppJsError',

    //授权登录
    GetOpenIdApi: 'api/AppLogin/GetOpenId', //获取openid
    OpenIdIsExistApi: 'api/AppLogin/OpenIdIsExist', //判断当前OpenID是否存在
    GetLoginOpenidApi: 'api/AppLogin/GetLoginMp', //带openid的登录

    //日常保洁
    GetCleanTaskListMobileApi: 'api/LanShengMobile/GetCleanTaskListMobile',//当日未保洁任务
    GetHistoryCleanTaskListMobileApi: 'api/LanShengMobile/GetHistoryCleanTaskListMobile', //历史保洁任务列表
    GetHistoryCleanTaskDetailsApi: 'api/LanShengMobile/GetHistoryCleanTaskDetails',//历史任务详情
    AddCleanRecordApi: 'api/LanShengMobile/AddCleanRecord',//添加保洁记录
    JugeRoomExistApi: 'api/LanShengMobile/JugeRoomExist',//扫一扫判断房间是否存在
    GetCleanTaskDetailsByRoomIDApi: 'api/LanShengMobile/GetCleanTaskDetailsByRoomID',//当日保洁任务详情
    GetHistoryCleanRoomApi: 'api/LanShengMobile/GetHistoryCleanRoom',//获取历史保洁任务房间列表

    //维保接口
    GetMaintenanceTaskHisMobileApi: 'api/LanShengMobile/GetMaintenanceTaskHisMobile',//获取历史维保任务列表,筛选
    GetEquipmentTypeApi: 'api/LanShengMobile/GetEquipmentType',//获取维保任务设备类型列表
    GetMaintenanceScanApi: 'api/LanShengMobile/GetMaintenanceScan',//维保扫一扫
    GetMasterSysDictionaryApi: 'api/LanShengMobile/GetMasterSysDictionary',//移动端设备信息查询，系统
    AddRecordListApi: "api/LanShengMobile/AddRecordList",   //新增维保记录
    GetMaintenanceTermApi: "api/LanShengMobile/GetMaintenanceTerm",   //获取维保项
    GetMaintenanceScreenApi: "api/LanShengMobile/GetMaintenanceScreen",   //维保首页筛选
    GetMaintenanceDetailsApi: "api/LanShengMobile/GetMaintenanceDetails",   //获取维保详情
    GetMasterSysPositionApi: 'api/LanShengMobile/GetMasterSysPosition',//获取维保任务设备类型列表
    GetMaterClassifyDictionaryApi: 'api/LanShengMobile/GetMaterClassifyDictionary',//获取设备分类(移动端设备信息查询，分类)
    GetDelegateExamineApi: 'api/LanShengMobile/GetDelegateExamine',//获取维保任务设备类型列表
  }
}